﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

[AddComponentMenu("PUEX/Emitter/FanEmitter")]
public class PUEXFanEmitter : PUEXEmitter {

	#region - Editable property
	[Header("FanEmitter:")]
	public float radius;
	public float angle;
	public float directionAngle;
	public bool emitOnSurface;
	public bool emitLinear;
	public bool flipLinear;
	public bool alignDirection;
	public float randomDeviant;
	#endregion

	#region - Property
	protected Vector3 _emitOffset;
	#endregion
	
	#region - Lifecycle
	public PUEXFanEmitter ()
	{
		radius = 20f;
		angle = 30f;
		directionAngle = 0f;
		emitOnSurface = false;
		emitLinear = false;
		flipLinear = false;
		alignDirection = true;
		randomDeviant = 0f;
	}
	#endregion

	#region - Emit
	protected override void initParticlePosition (PUEXParticle particle, int index, int requested)
	{
		if (emitLinear) {
			float r = radius;
			if (emitOnSurface == false) {
				r = timeFraction * radius;
				if (flipLinear)
					r = (1f - timeFraction) * radius;
			}
			
			float a = (angle * Mathf.Deg2Rad / 2f) + ((float)index + 0.5f) / (float)requested * -(angle * Mathf.Deg2Rad);
			float x = Mathf.Cos (a) * r;
			float y = Mathf.Sin (a) * r;
			_emitOffset = new Vector3(y, 0f, x);
		} else {
			float r = radius;
			if (emitOnSurface == false)
				r = Random.value * radius;

			float a = (angle * Mathf.Deg2Rad / 2f) + Random.value * -(angle * Mathf.Deg2Rad);
			float x = Mathf.Cos (a) * r;
			float y = Mathf.Sin (a) * r;
			_emitOffset = new Vector3(y, 0f, x);
		}
		
		particle.position = particle.originalPosition = emitterToSimulationTransform.MultiplyPoint (_emitOffset);
	}
	
	protected override void initParticleVelocity (PUEXParticle particle, int index, int requested)
	{
		if (alignDirection) {
			Vector3 dir = _emitOffset;

			if (directionAngle > 0f) {
				Vector3 pAxis = Vector3.Cross(dir, Vector3.up);
				dir = Quaternion.AngleAxis(directionAngle, pAxis) * dir;
			}
			
			if (randomDeviant > 0f) {
				dir = PUEXUtils.randomDeviant(dir, randomDeviant);
			}
			
			particle.direction = particle.originalDirection = emitterToSimulationTransform.MultiplyVector (dir).normalized;
		} else {
			particle.direction = particle.originalDirection = emitterToSimulationTransform.MultiplyVector (Random.insideUnitSphere).normalized;
		}
		
		particle.speed = particle.originalSpeed = startSpeed.getValue (timeFraction);
	}
	#endregion

	#region - Serialization
	public override JsonData save (JsonData systemData)
	{
		JsonData ret = base.save (systemData);
		
		ret ["radius"] = radius;
		ret ["angle"] = angle;
		ret ["direction_angle"] = directionAngle;
		ret ["emit_on_surface"] = emitOnSurface;
		ret ["emit_linear"] = emitLinear;
		ret ["flip_linear"] = flipLinear;
		ret ["align_direction"] = alignDirection;
		ret ["random_deviant"] = randomDeviant;
		
		return ret;
	}
	#endregion

}
